package com.mit.wx.controller;

import com.mit.wx.wx.dto.CustomerServiceAccount;
import com.mit.wx.wx.dto.CustomerServiceMessage;
import com.mit.wx.entity.WxUser;
import com.mit.wx.service.AccessTokenService;
import com.mit.wx.service.WxUserService;
import com.mit.wx.vo.BasicJsonResult;
import com.mit.wx.wx.dto.BasicWxResponse;
import com.mit.wx.wx.WxKfApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * 2018/10/9 Create by 郭文梁
 * CustomerServiceController
 * 客服访问控制器
 *
 * @author 郭文梁
 * @date 2018/10/9
 */
@Slf4j
@RestController
@RequestMapping("/kf")
public class CustomerServiceController {
    private final WxUserService wxUserService;
    private final AccessTokenService accessTokenService;

    @Autowired
    public CustomerServiceController(AccessTokenService accessTokenService, WxUserService wxUserService) {
        this.accessTokenService = accessTokenService;
        this.wxUserService = wxUserService;
    }

    @PostMapping("/send-text")
    public BasicJsonResult<BasicWxResponse> sendText(int userId, String msg) throws IOException {
        WxUser user = wxUserService.findById(userId);
        if (user == null) {
            return BasicJsonResult.error(1, "用户不存在");
        }
        CustomerServiceMessage message = new CustomerServiceMessage()
                .text(msg)
                .toUser(user.getOpenId());
        String accessToken = accessTokenService.getAccessToken().getAccessToken();
        BasicWxResponse response = WxKfApi.sendKfMessage(accessToken, message);
        return BasicJsonResult.ok(response);
    }

    @GetMapping("/all")
    public List<CustomerServiceAccount> allAccount() throws IOException {
        String accessToken = accessTokenService.getAccessToken().getAccessToken();
        return WxKfApi.getCustomerServiceList(accessToken);
    }

    @PostMapping("/create")
    public BasicJsonResult<BasicWxResponse> create(CustomerServiceAccount account) throws IOException {
        BasicWxResponse response = WxKfApi.createCustomerService(
                accessTokenService.getAccessToken().getAccessToken(),
                account);
        return BasicJsonResult.ok(response);
    }
}
